package com.cms.controller.front;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.util.Base64;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.cms.Config;
import com.cms.Feedback;
import com.cms.entity.Member;
import com.cms.entity.MessageConfig;
import com.cms.entity.SafeKey;
import com.cms.routes.RouteMapping;
import com.cms.util.DeviceUtils;
import com.cms.util.MapUrlParamsUtils;
import com.cms.util.QqUtils;
import com.cms.util.SystemUtils;
import com.cms.util.WeixinUtils;

/**
 * Controller - 登录
 * 
 * 
 * 
 */
@RouteMapping(url = "/login")
public class LoginController extends BaseController{
	
	/**
	 * 登录页面
	 */
	public void index(){
		render("/templates/"+getTheme()+"/"+getDevice()+"/login.html");
	}
	
	/**
	 * 短信登录
	 */
	public void sms(){
		String username = getPara("username");
		String code = getPara("code");
		SafeKey safeKey = new SafeKey().dao().findByMobile(username, MessageConfig.Type.LOGIN.ordinal());
		if(!(safeKey.getValue().equals(code))){
			renderJson(Feedback.error("短信验证码错误"));
			return;
		}
		Member member = new Member().dao().findByMobile(username);
        if(member == null){
            renderJson(Feedback.error("用户不存在"));
            return;
        }else{
            getSession().setAttribute(Member.SESSION_MEMBER, member);
            renderJson(Feedback.success(new HashMap<>()));
            return;
        }
	}

	/**
	 * 密码登录
	 */
	public void password(){
		String username = getPara("username");
        String password = getPara("password");
        if(StringUtils.isBlank(username) || StringUtils.isBlank(password)){
        	renderJson(Feedback.error("参数错误"));
        	return;
        }
        Member member = new Member().dao().findByMobile(username);
        if(member == null){
            renderJson(Feedback.error("用户不存在"));
            return;
        }else if(!DigestUtils.md5Hex(password).equals(member.getPassword())){
            renderJson(Feedback.error("用户名密码错误"));
            return;
        }else{
            getSession().setAttribute(Member.SESSION_MEMBER, member);
            renderJson(Feedback.success(new HashMap<>()));
            return;
        }
	}
	
	
    /**
     * 微信登录
     */
    public void weixin(){
        try {
            Config config = SystemUtils.getConfig();
            if(DeviceUtils.isWechat(getRequest())){
            	//公众号
            	getResponse().sendRedirect(WeixinUtils.getAuthorizeUrl(URLEncoder.encode(config.getSiteUrl()+"/login/weixinReturn", "UTF-8"), "STATE"));
            }else{
            	//PC微信登录
            	getResponse().sendRedirect(WeixinUtils.getQrconnectUrl(URLEncoder.encode(config.getSiteUrl()+"/login/weixinReturn", "UTF-8"), "STATE"));
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        renderNull();
    }
    
    
    /**
     * 微信登录同步
     */
    public void weixinReturn(){
        String code = getPara("code");
        String state = getPara("state");
        String mapJson = "";
		try {
			mapJson = new String(Base64.decodeBase64(state),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Map<String, String> map = JSONObject.parseObject(mapJson, new TypeReference<Map<String, String>>(){});
        String newUrl = map.get("newUrl");
        String queryString = map.get("queryString");
        String qrcode = "";
        if(StringUtils.isNotBlank(queryString)){
        	Map<String,Object> param = MapUrlParamsUtils.getUrlParams(queryString);
        	if(param.get("qrcode")!=null){
        		qrcode = param.get("qrcode").toString();
        	}
        }
        Map<String,Object> token = WeixinUtils.getOauth2Token(code);
        String openId = (String)token.get("openid");
        String accessToken = (String)token.get("access_token");
        Member member = new Member().dao().findByWeixinOpenId(openId);
        if(member==null){
        	//获取用户信息
            Map<String,Object> userInfo = WeixinUtils.getOauth2Userinfo(accessToken,openId);
            member = new Member();
            //附件信息
            String newcode = new Member().dao().findCode();
            if(StringUtils.isNotBlank(qrcode)){
    			Member parentMember = new Member().dao().findByCode(qrcode);
    			member.setParentId(parentMember.getId());
    		}
            member.setCode(newcode);
    		member.setValue();
            member.setCreateDate(new Date());
            member.setModifyDate(new Date());
            member.setNickname(Base64.encodeBase64String(((String)userInfo.get("nickname")).getBytes()));
            member.setAvatar((String)userInfo.get("headimgurl"));
            member.setWeixinOpenId(openId);
            member.save();
        }
        getSession().setAttribute(Member.SESSION_MEMBER,member);
        if(StringUtils.isNotBlank(queryString)){
        	redirect(newUrl+"?"+queryString);
        	return;
        }
        redirect(newUrl);
    }
    
    /**
     * QQ登录同步
     */
    public void qqReturn(){
    	Config config = SystemUtils.getConfig();
        String code = getPara("code");
        try{
        	Map<String,Object> accessTokenMap = QqUtils.getOauth2Token(code,URLEncoder.encode(config.getSiteUrl()+"/login/qqReturn", "UTF-8"));
        	String accessToken = (String)accessTokenMap.get("access_token");
        	Map<String,Object> openIdMap = QqUtils.getOpenId(accessToken);
        	String openId = (String)openIdMap.get("openid");
        	Member member = new Member().dao().findByQqOpenId(openId);
        	if(member==null){
        		//获取用户信息
        		Map<String,Object> userInfo = QqUtils.getUserInfo(accessToken,openId);
        		member = new Member();
        		member.setCreateDate(new Date());
        		member.setModifyDate(new Date());
        		member.setNickname((String)userInfo.get("nickname"));
        		member.setAvatar((String)userInfo.get("figureurl"));
        		member.setQqOpenId(openId);
        		member.setAmount(BigDecimal.ZERO);
        		member.save();
        	}
        	getSession().setAttribute(Member.SESSION_MEMBER,member);
        	redirect("/");
        }catch (Exception e) {
			// TODO: handle exception
        	e.printStackTrace();
        }
    }
}
